<template>
  <page-header-wrapper>
    <a-card>
      <JeepaySearchForm :searchFunc="searchFunc" :resetFunc="() => { vdata.searchData = {} }">
        <jeepay-text-up v-model:value="vdata.searchData['storeId']" :placeholder="'门店ID'" />
        <jeepay-text-up v-model:value="vdata.searchData['storeName']" :placeholder="'门店名称'" />
      </JeepaySearchForm>
      <!-- 列表渲染 -->
      <JeepayTable
        ref="infoTable"
        :initData="true"
        :reqTableDataFunc="reqTableDataFunc"
        :tableColumns="tableColumns"
        :searchData="vdata.searchData"
        rowKey="storeId"
        @btnLoadClose="vdata.btnLoading=false"
      >
        <template #topBtnSlot>
          <div>
            <a-button v-if="$access('ENT_MCH_STORE_ADD')" type="primary" class="mg-b-30" @click="addFunc"><plus-outlined />新建</a-button>
          </div>
        </template>
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'storeName'">
            <a @click="detailFunc(record.storeId)"><b>{{ record.storeName }}</b></a>
          </template>
          <template v-if="column.key === 'defaultFlag'">
            <a-tag v-if="record.defaultFlag===1" color="green">是</a-tag>
            <a-switch v-else :checked="record.defaultFlag===1?true:false" @change="(defaultFlag) => { return updateState(record.storeId, defaultFlag)}" />
          </template>
          <template v-if="column.key === 'alipayShopStatus'">
            <a-tag v-if="record.alipayShopStatus=='0'" />
            <a-tag v-else-if="record.alipayShopStatus=='99'" color="green">审核通过</a-tag>
            <a-tag v-else-if="record.alipayShopStatus=='-1'" color="red">审核拒绝</a-tag>
            <div v-else>
              <a-tag color="orange">审核中</a-tag>
              <a-tag
                v-if="$access('ENT_MCH_ALIPAY_SHOP_STATUS')"
                color="blue"
                style="cursor: pointer;"
                @click="updateAlipayShopStatusFunc(record.storeId)"
              >
                <sync-outlined />更新状态
              </a-tag>
            </div>
          </template>

          <template v-if="column.key === 'op'">
            <!-- 操作列插槽 -->
            <JeepayTableColumns>
              <a-button v-if="$access('ENT_MCH_STORE_EDIT')" type="link" style="padding-right: 10px;padding-left: 10px;" @click="editFunc(record.storeId)">修改</a-button>
              <a-button v-if="$access('ENT_MCH_STORE_APP_DIS')" type="link" @click="open(record)">应用分配</a-button>
              <a-button type="link" @click="workRecordFunc(record)">交接班记录</a-button>
              <a-button v-if="$access('ENT_MCH_ALIPAY_SHOP_ADD') && record.alipayShopStatus == '0'" type="link" @click="alipayShopCreateFunc(record.storeId)">创建蚂蚁店铺</a-button>
              <a-button v-if="$access('ENT_MCH_ALIPAY_SHOP_EDIT') && record.alipayShopStatus != '0' && record.alipayShopId" type="link" @click="alipayShopUpdateFunc(record.storeId)">修改蚂蚁店铺</a-button>
              <a-button v-if="$access('ENT_MCH_STORE_DELETE')" type="link" style="color: red" @click="delFunc(record.storeId)">删除</a-button>
            </JeepayTableColumns>
          </template>
        </template>
      </JeepayTable>
    </a-card>

    <!-- 新增 / 修改 页面组件  -->
    <InfoAddOrEdit ref="infoAddOrEdit" :callbackFunc="searchFunc" />
    <!-- 蚂蚁店铺 页面组件  -->
    <AlipayShop ref="alipayShopRef" :callbackFunc="searchFunc" />
    <!-- 详情页面组件  -->
    <InfoDetail ref="infoDetail" :callback-func="searchFunc" />
    <!--    应用分配页面-->
    <AppBind ref="appBind" :callbackFunc="searchFunc" />
    <!-- 交接班记录页面 -->
    <WorkRecord ref="workRecord" :callbackFunc="searchFunc" />
  </page-header-wrapper>
</template>
<script lang="ts" setup>
import { API_URL_MCH_STORE_LIST, req, reqLoad, API_ALIPAY_SHOP } from '@/api/manage'
import { useUserStore } from '@/store/modules/user'

import InfoAddOrEdit from './AddOrEdit.vue'
import AlipayShop from './AlipayShop.vue'
import InfoDetail from './Detail.vue'
import WorkRecord from './WorkRecord.vue'
import  AppBind from './components/AppBind.vue'
import { ref, onMounted, reactive, getCurrentInstance } from 'vue'
// 获取全局函数
const { $infoBox,$access } = getCurrentInstance()!.appContext.config.globalProperties

const userStore = useUserStore()

// tableColumns 顺序不可随意修改 （关联下方列显示）
const tableColumns = reactive([
  { title: '门店名称', key: 'storeName', dataIndex: 'storeName' },
  { title: '门店编号', dataIndex: 'storeId', fixed: 'left' },
  { title: '是否默认', key: 'defaultFlag', align: 'center' },
  { title: 'AppId', dataIndex: 'bindAppId' },
  { title: '蚂蚁店铺状态', key: 'alipayShopStatus', dataIndex: 'alipayShopStatus' },
  { title: '创建时间', dataIndex: 'createdAt' },
  { key: 'op',title: '操作', fixed: 'right', align: 'center'}
])

// 如果用户类型为店长、店员时
if(userStore.userInfo['userType'] == 11 || userStore.userInfo['userType'] == 12) {
  // 删除是否默认的列展示
  tableColumns.splice(2, 1)
}

    const infoDetail = ref()
    const infoAddOrEdit  =ref()
    const alipayShopRef  =ref()
    const infoTable =ref()
    const appBind = ref()
    const workRecord = ref()
    const vdata = reactive({
      tableColumns: tableColumns,
      searchData: {},
      btnLoading: false
    })

    // 请求table接口数据
   function reqTableDataFunc (params)  {
      return req.list(API_URL_MCH_STORE_LIST, params)
    }
   function searchFunc() { // 点击【查询】按钮点击事件
      vdata.btnLoading = true // 打开查询按钮的loading
      infoTable.value.refTable(true)
    }
  function  addFunc () { // 业务通用【新增】 函数
      infoAddOrEdit.value.show()
    }
  function  delFunc (recordId) { // 业务通用【删除】 函数
    
      $infoBox.confirmDanger('确认删除？', '', () => {
        return req.delById(API_URL_MCH_STORE_LIST, recordId).then(res => {
         $infoBox.message.success('删除成功！')
          infoTable.value.refTable(false)
        }).catch(err => {})
      })
    }
  function editFunc (recordId) { // 业务通用【修改】 函数
    infoAddOrEdit.value.show(recordId)
  }
  function alipayShopCreateFunc (recordId) { // 创建蚂蚁店铺
    alipayShopRef.value.show(recordId, true)
  }
  function alipayShopUpdateFunc (recordId) { // 更新蚂蚁店铺
    alipayShopRef.value.show(recordId, false)
  }
  function detailFunc (recordId: any) { // 门店详情页
      infoDetail.value.show(recordId)
    }
  function open (record: any) { // 门店详情页
    appBind.value.open(record)
  }
  function workRecordFunc (record: any) { // 相应门店交接班记录
    workRecord.value.show(record)
  }
  function updateState (recordId, state) { // 【更新状态】
    const title = state === 1 ? '确认[默认]该门店？' : '确认[取消默认]该门店？'
    const content = '开启默认后则默认使用该门店配置，有且只能有一个默认门店。'
    return new Promise<void>((resolve, reject) => {
      $infoBox.confirmDanger(title, content, () => {
        return reqLoad.updateById(API_URL_MCH_STORE_LIST, recordId, { defaultFlag: state }).then(res => {
          searchFunc()
          resolve()
        }).catch(err => reject(err))
      },
        () => {
        reject(new Error())
      })
    })
  }
  function updateAlipayShopStatusFunc (recordId) { // 【更新蚂蚁店铺状态】
    return new Promise<void>((resolve, reject) => {
      reqLoad.getById(API_ALIPAY_SHOP + '/createResult', recordId, undefined).then(res => {
        vdata.btnLoading = false
        searchFunc()
      }).catch(valid =>{
        vdata.btnLoading = false
      })
    })
  }

</script>
